<template>
  <div class="region-select">
    <!-- 三级联动选择器 -->
    <div v-if="mode === 'cascader'" class="cascader-mode">
      <el-cascader
        v-model="cascaderValue"
        :options="cascaderOptions"
        :props="cascaderProps"
        :placeholder="placeholder"
        :disabled="disabled"
        :clearable="clearable"
        :show-all-levels="showAllLevels"
        :size="size"
        :filterable="filterable"
        style="width: 100%"
        @change="handleCascaderChange"
      />
    </div>
    
    <!-- 分级选择器 -->
    <div v-else class="select-mode">
      <el-row :gutter="8">
        <!-- 省份选择 -->
        <el-col :span="levelSpan">
          <el-select
            v-model="selectedProvince"
            placeholder="请选择省份"
            :disabled="disabled"
            :clearable="clearable"
            :size="size"
            :filterable="filterable"
            style="width: 100%"
            @change="handleProvinceChange"
          >
            <el-option
              v-for="province in provinces"
              :key="province.regionId"
              :label="province.regionName"
              :value="province.regionId"
            />
          </el-select>
        </el-col>
        
        <!-- 城市选择 -->
        <el-col v-if="level >= 2" :span="levelSpan">
          <el-select
            v-model="selectedCity"
            placeholder="请选择城市"
            :disabled="disabled || !selectedProvince"
            :clearable="clearable"
            :size="size"
            :filterable="filterable"
            style="width: 100%"
            @change="handleCityChange"
          >
            <el-option
              v-for="city in cities"
              :key="city.regionId"
              :label="city.regionName"
              :value="city.regionId"
            />
          </el-select>
        </el-col>
        
        <!-- 区县选择 -->
        <el-col v-if="level >= 3" :span="levelSpan">
          <el-select
            v-model="selectedDistrict"
            placeholder="请选择区县"
            :disabled="disabled || !selectedCity"
            :clearable="clearable"
            :size="size"
            :filterable="filterable"
            style="width: 100%"
            @change="handleDistrictChange"
          >
            <el-option
              v-for="district in districts"
              :key="district.regionId"
              :label="district.regionName"
              :value="district.regionId"
            />
          </el-select>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { getProvinces, getCitiesByProvinceId, getDistrictsByCityId } from '@/api/system/region'

export default {
  name: 'RegionSelect',
  props: {
    // v-model 绑定的值
    value: {
      type: [Array, Object],
      default: () => []
    },
    // 显示模式：'cascader' 级联选择器，'select' 分级选择器
    mode: {
      type: String,
      default: 'cascader',
      validator(value) {
        return ['cascader', 'select'].includes(value)
      }
    },
    // 级联层级（1=省份，2=城市，3=区县）
    level: {
      type: Number,
      default: 3,
      validator(value) {
        return [1, 2, 3].includes(value)
      }
    },
    // 占位符
    placeholder: {
      type: String,
      default: '请选择地区'
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false
    },
    // 是否可清空
    clearable: {
      type: Boolean,
      default: true
    },
    // 是否显示完整路径
    showAllLevels: {
      type: Boolean,
      default: true
    },
    // 尺寸
    size: {
      type: String,
      default: ''
    },
    // 是否可搜索
    filterable: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 级联选择器的值
      cascaderValue: [],
      // 分级选择器的值
      selectedProvince: null,
      selectedCity: null,
      selectedDistrict: null,
      // 选项数据
      provinces: [],
      cities: [],
      districts: [],
      cascaderOptions: [],
      cascaderProps: {
        value: 'regionId',
        label: 'regionName',
        children: 'children',
        lazy: true,
        lazyLoad: this.lazyLoadCascader
      }
    }
  },
  computed: {
    // 计算每个选择器的栅格大小
    levelSpan() {
      return Math.floor(24 / this.level)
    }
  },
  watch: {
    value: {
      handler(val) {
        this.initValue(val)
      },
      immediate: true
    }
  },
  created() {
    this.loadProvinces()
    if (this.mode === 'cascader') {
      this.loadCascaderProvinces()
    }
  },
  methods: {
    // 初始化值
    initValue(val) {
      if (this.mode === 'cascader') {
        this.cascaderValue = Array.isArray(val) ? val : []
      } else {
        if (Array.isArray(val)) {
          this.selectedProvince = val[0] || null
          this.selectedCity = val[1] || null
          this.selectedDistrict = val[2] || null
        } else if (val && typeof val === 'object') {
          this.selectedProvince = val.province || null
          this.selectedCity = val.city || null
          this.selectedDistrict = val.district || null
        }
        
        // 如果有选中的省份，加载城市
        if (this.selectedProvince) {
          this.loadCities(this.selectedProvince)
        }
        // 如果有选中的城市，加载区县
        if (this.selectedCity) {
          this.loadDistricts(this.selectedCity)
        }
      }
    },
    
    // 级联选择器懒加载
    async lazyLoadCascader(node, resolve) {
      const { level, value } = node
      let children = []
      
      try {
        if (level === 0) {
          // 加载省份
          const response = await getProvinces()
          children = response.data || []
        } else if (level === 1 && this.level >= 2) {
          // 加载城市
          const response = await getCitiesByProvinceId(value)
          children = response.data || []
        } else if (level === 2 && this.level >= 3) {
          // 加载区县
          const response = await getDistrictsByCityId(value)
          children = response.data || []
        }
        
        // 设置leaf属性
        children.forEach(item => {
          if (this.level === 1) {
            item.leaf = true
          } else if (this.level === 2) {
            item.leaf = level >= 1
          } else {
            item.leaf = level >= 2
          }
        })
        
        resolve(children)
      } catch (error) {
        console.error('加载地区数据失败:', error)
        resolve([])
      }
    },
    
    // 加载级联选择器省份数据
    async loadCascaderProvinces() {
      try {
        const response = await getProvinces()
        const provinces = response.data || []
        
        provinces.forEach(province => {
          province.leaf = this.level === 1
        })
        
        this.cascaderOptions = provinces
      } catch (error) {
        console.error('加载省份数据失败:', error)
      }
    },
    
    // 加载省份
    async loadProvinces() {
      try {
        const response = await getProvinces()
        this.provinces = response.data || []
      } catch (error) {
        console.error('加载省份数据失败:', error)
      }
    },
    
    // 加载城市
    async loadCities(provinceId) {
      if (!provinceId) {
        this.cities = []
        return
      }
      
      try {
        const response = await getCitiesByProvinceId(provinceId)
        this.cities = response.data || []
      } catch (error) {
        console.error('加载城市数据失败:', error)
        this.cities = []
      }
    },
    
    // 加载区县
    async loadDistricts(cityId) {
      if (!cityId) {
        this.districts = []
        return
      }
      
      try {
        const response = await getDistrictsByCityId(cityId)
        this.districts = response.data || []
      } catch (error) {
        console.error('加载区县数据失败:', error)
        this.districts = []
      }
    },
    
    // 级联选择器值变化
    handleCascaderChange(value) {
      this.$emit('input', value)
      this.$emit('change', value)
    },
    
    // 省份变化
    handleProvinceChange(value) {
      this.selectedProvince = value
      this.selectedCity = null
      this.selectedDistrict = null
      this.cities = []
      this.districts = []
      
      if (value) {
        this.loadCities(value)
      }
      
      this.emitChange()
    },
    
    // 城市变化
    handleCityChange(value) {
      this.selectedCity = value
      this.selectedDistrict = null
      this.districts = []
      
      if (value) {
        this.loadDistricts(value)
      }
      
      this.emitChange()
    },
    
    // 区县变化
    handleDistrictChange(value) {
      this.selectedDistrict = value
      this.emitChange()
    },
    
    // 发出变化事件
    emitChange() {
      const values = [this.selectedProvince, this.selectedCity, this.selectedDistrict]
        .filter(v => v != null)
      
      this.$emit('input', values)
      this.$emit('change', values)
    }
  }
}
</script>

<style lang="scss" scoped>
.region-select {
  width: 100%;
}
</style>